const nodemailer = require("nodemailer");

class EmailServices {
  // 统一响应函数
  handleResponse(data, error, notFoundMessage = "实体未找到") {
    if (error) {
      return {
        code: 1,
        msg: error.message || "发生错误",
        statusCode: error.statusCode || 500,
      };
    }
    if (!data) {
      return {
        code: 1,
        msg: notFoundMessage,
        statusCode: 404,
      };
    }
    return { code: 0, data: data };
  }

  // 邮件发送函数
  async sendEmail(to, content) {
    try {
      // 创建SMTP客户端
      const transporter = nodemailer.createTransport({
        host: "smtp.qq.com", // QQ邮箱的SMTP服务器
        port: 465,
        secure: true,
        auth: {
          user: "smartcabinets@qq.com", // 邮箱账号
          pass: "dhdccqxyhtnudacb", // 授权码
        },
      });

      // 邮件内容
      const mailOptions = {
        from: "smartcabinets@qq.com", // 发件人邮箱
        to: to, // 收件人邮箱
        subject: "智柜团队", // 邮件主题
        text: content, // 邮件正文
      };

      // 发送邮件
      const info = await transporter.sendMail(mailOptions);
      return this.handleResponse("success", null);
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }
}

module.exports = new EmailServices();
